<template>
  <div class="balance-container">
    <el-card class="balance-card">
      <template #header>
        <div class="card-header">
          <span>我的余额</span>
        </div>
      </template>
      <div class="balance-content" v-loading="loading">
        <div class="balance-amount">
          <h2>¥{{ balance.toFixed(2) }}</h2>
        </div>
        <div class="balance-actions">
          <el-button type="primary" @click="showRechargeDialog">充值</el-button>
          <el-button type="warning" @click="showWithdrawDialog">提现</el-button>
        </div>
      </div>
    </el-card>

    <!-- 充值对话框 -->
    <el-dialog
      title="充值"
      v-model="rechargeDialogVisible"
      width="30%"
    >
      <el-form :model="rechargeForm" :rules="rechargeRules" ref="rechargeFormRef" label-width="80px">
        <el-form-item label="充值金额" prop="amount">
          <el-input v-model.number="rechargeForm.amount" type="number" min="0.01" placeholder="请输入充值金额">
            <template #prefix>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="rechargeForm.remark" placeholder="请输入备注（选填）"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rechargeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRecharge" :loading="submitting">确认充值</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 提现对话框 -->
    <el-dialog
      title="提现"
      v-model="withdrawDialogVisible"
      width="30%"
    >
      <el-form :model="withdrawForm" :rules="withdrawRules" ref="withdrawFormRef" label-width="80px">
        <el-form-item label="提现金额" prop="amount">
          <el-input v-model.number="withdrawForm.amount" type="number" min="0.01" :max="balance" placeholder="请输入提现金额">
            <template #prefix>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="withdrawForm.remark" placeholder="请输入备注（选填）"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="withdrawDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleWithdraw" :loading="submitting">确认提现</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { getUserBalance, operateBalance } from '@/api/user'
import { ElMessage } from 'element-plus'

// 余额数据
const balance = ref(0)
const loading = ref(false)

// 充值相关
const rechargeDialogVisible = ref(false)
const rechargeForm = ref({
  amount: '',
  remark: '',
  type: 1 // 1-充值
})
const rechargeFormRef = ref(null)
const rechargeRules = {
  amount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' }
  ]
}

// 提现相关
const withdrawDialogVisible = ref(false)
const withdrawForm = ref({
  amount: '',
  remark: '',
  type: 2 // 2-提现
})
const withdrawFormRef = ref(null)
const withdrawRules = {
  amount: [
    { required: true, message: '请输入提现金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value > balance.value) {
          callback(new Error('提现金额不能大于余额'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

const submitting = ref(false)

// 获取用户余额
const fetchUserBalance = async () => {
  loading.value = true
  try {
    const response = await getUserBalance()
    if (response.code === 200) {
      balance.value = response.data.balance
    }
  } catch (error) {
    console.error('获取余额失败:', error)
    ElMessage.error('获取余额失败')
  } finally {
    loading.value = false
  }
}

// 显示充值对话框
const showRechargeDialog = () => {
  rechargeForm.value = {
    amount: '',
    remark: '',
    type: 1
  }
  rechargeDialogVisible.value = true
}

// 显示提现对话框
const showWithdrawDialog = () => {
  withdrawForm.value = {
    amount: '',
    remark: '',
    type: 2
  }
  withdrawDialogVisible.value = true
}

// 处理充值
const handleRecharge = async () => {
  if (!rechargeFormRef.value) return
  
  await rechargeFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const response = await operateBalance(rechargeForm.value)
        if (response.code === 200) {
          ElMessage.success('充值成功')
          rechargeDialogVisible.value = false
          balance.value = response.data.balance
        } else {
          ElMessage.error(response.message || '充值失败')
        }
      } catch (error) {
        console.error('充值失败:', error)
        ElMessage.error('充值失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 处理提现
const handleWithdraw = async () => {
  if (!withdrawFormRef.value) return
  
  await withdrawFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const response = await operateBalance(withdrawForm.value)
        if (response.code === 200) {
          ElMessage.success('提现成功')
          withdrawDialogVisible.value = false
          balance.value = response.data.balance
        } else {
          ElMessage.error(response.message || '提现失败')
        }
      } catch (error) {
        console.error('提现失败:', error)
        ElMessage.error('提现失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 页面加载时获取余额
onMounted(() => {
  fetchUserBalance()
})
</script>

<style scoped>
.balance-container {
  padding: 20px 0;
}

.balance-card {
  max-width: 600px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.balance-content {
  text-align: center;
  padding: 20px 0;
}

.balance-amount {
  margin-bottom: 20px;
}

.balance-amount h2 {
  font-size: 36px;
  color: #409EFF;
  margin: 0;
}

.balance-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}
</style>
